const cfg = require("../config/config");
const jwt = require("jsonwebtoken");

const jwtMiddleWare = ((req, res, next) => {
    // 如果是OPTIONS请求，直接放行
    if (req.method === "OPTIONS") {
        next();
        return;
    }

    // 如果没有authorization头，直接放行
    if (!req.headers.authorization) {
        next();
        return;
    }

    // 解析jwt凭证，校验，提取user
    jwt.verify(req.headers.authorization, cfg.jwtSecret, (err, data) => {
        if (err) {
            console.log(err);
            res.send({code: 4001, msg: '凭证过期或校验失败，请重新登录', data: null});
            return;
        }
        req.user = data;
        next();
    });
});

module.exports = jwtMiddleWare;